package co.fitstart.admin.web.controller.user.agent;

import java.util.List;

import javax.servlet.http.HttpServletRequest;

import org.apache.commons.lang3.StringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.servlet.ModelAndView;

import com.demo2do.core.BusinessException;
import com.demo2do.core.support.Page;
import com.demo2do.core.support.Result;
import com.demo2do.core.utils.JsonUtils;
import com.demo2do.core.web.resolver.Preloading;
import com.demo2do.core.web.utils.WebUtils;

import co.fitstart.admin.entity.search.AgentSearch;
import co.fitstart.admin.service.AgentService;
import co.fitstart.admin.service.UserService;
import co.fitstart.admin.web.interceptor.MenuSetting;
import co.fitstart.admin.web.view.ExcelTemplateView;
import co.fitstart.entity.user.User;
import co.fitstart.entity.user.agent.Agent;
import co.fitstart.entity.user.agent.AgentDiscount;
import co.fitstart.entity.user.agent.DiscountType;

@Controller
@RequestMapping("/agents")
@MenuSetting("menu-user")
public class OnlineAgentController {
    
    private static final Logger logger = LoggerFactory.getLogger(OnlineAgentController.class);
    
    @Autowired
    private UserService userService;
    
    @Autowired
    private AgentService agentService;
    
    /**
     * 
     * @param page
     * @param request
     * @return
     */
    @RequestMapping(value = "", method = RequestMethod.GET)
    @MenuSetting("submenu-online-agent")
    public ModelAndView list(Page page, HttpServletRequest request) {
        ModelAndView modelAndView = new ModelAndView("user/agent/agent-list");
        
        List<Agent> agents = agentService.listAgent(page);
        modelAndView.addObject("agents", agents);
        
        modelAndView.addObject("page", page);
        
        modelAndView.addObject("refer", "list");
        modelAndView.addObject("queryString", WebUtils.extractQueryString(request, "page"));
        
        return modelAndView;
    }
    
    /**
     * 
     * @return
     */
    @RequestMapping(value = "/search", method = RequestMethod.GET)
    public ModelAndView search() {
        ModelAndView modelAndView = new ModelAndView("user/agent/agent-search");
        return modelAndView;
    }
    
    /**
     * 
     * @param agentSearch
     * @param page
     * @param request
     * @return
     */
    @RequestMapping(value = "", method = RequestMethod.GET, params = "filter")
    @MenuSetting("submenu-online-agent")
    public ModelAndView onSearch(AgentSearch agentSearch, Page page, HttpServletRequest request) {
        ModelAndView modelAndView = new ModelAndView("user/agent/agent-list");
        
        List<Agent> agents = agentService.search(agentSearch, page);
        
        modelAndView.addObject("agents", agents);
        
        modelAndView.addObject("page", page);
        
        modelAndView.addObject("refer", "list");
        modelAndView.addObject("queryString", WebUtils.extractQueryString(request, "page"));
        
        return modelAndView;
    }
    
    /**
     * 
     * @param agentId
     * @return
     */
    @RequestMapping(value = "/{agentId}", method = RequestMethod.GET)
    @MenuSetting("submenu-online-agent")
    public ModelAndView view(@PathVariable("agentId") Long agentId) {
        ModelAndView modelAndView = new ModelAndView("user/agent/agent-view");
        
        Agent agent = agentService.loadAgent(agentId);
        modelAndView.addObject("agent", agent);
        
        List<AgentDiscount> agentDiscounts = agentService.listAgentDiscount(agent);
        modelAndView.addObject("agentDiscounts", agentDiscounts);
        
        return modelAndView;
    }
    
    /**
     * 
     * @return
     */
    @RequestMapping(value = "/create", method = RequestMethod.GET)
    public ModelAndView create() {
        ModelAndView modelAndView = new ModelAndView("user/agent/agent-create");
        return modelAndView;
    }
    
    /**
     * 
     * @param agent
     * @param discountOffer
     * @param commission
     * @param agentDiscount
     * @param userDiscounts
     * @return
     */
    @RequestMapping(value = "", method = RequestMethod.POST)
    public @ResponseBody String onCreate(Agent agent,
                                         @RequestParam(value = "discountType") String discountType,
                                         @RequestParam(value = "discountOffer", required = false) String discountOffer,
                                         @RequestParam(value = "commission", required = false) String commission,
                                         @RequestParam(value = "agentDiscount", required = false) Integer agentDiscount,
                                         @RequestParam(value = "userDiscount", required = false) String userDiscounts) {
        Result result = new Result();
        
        try {
            agentService.create(agent, DiscountType.aliasOf(discountType), discountOffer, commission, agentDiscount, userDiscounts);
            
            result.success().message("创建代言人成功");
            
        } catch (BusinessException e) {
            
            result.fail().message(e.getMessage());
            
        } catch (Exception e) {
            
            logger.error("onCreate() - ", e);
            result.fail().message("创建代言人失败");
        }
        
        return JsonUtils.toJsonString(result);
    }
    
    /**
     * 
     * @param mobile
     * @return
     */
    @RequestMapping(value = "", method = RequestMethod.GET, params = "filters")
    public @ResponseBody String onSearchUser(@RequestParam("mobile") String mobile) {
        Result result = new Result();
        
        try {
            
            User user = userService.load(mobile);
            String name = StringUtils.isEmpty(user.getName()) ? user.getMobile() : user.getName();
            result.success().data("username", name)
                            .data("userId", user.getId())
                            .message("查询用户成功");
            
        } catch (BusinessException e) {
            
            result.fail().message(e.getMessage());
            
        } catch (Exception e) {
            
            logger.error("onSearchUser() - ", e);
            result.fail().message("查询用户失败");
        }
        
        return JsonUtils.toJsonString(result);
    }
    
    /**
     * 
     * @param agentId
     * @return
     */
    @RequestMapping(value = "/{agentId}/delete", method = RequestMethod.GET)
    public ModelAndView delete(@PathVariable("agentId") Long agentId) {
        ModelAndView modelAndView = new ModelAndView("user/agent/agent-delete");
        
        modelAndView.addObject("agentId", agentId);
        
        return modelAndView;
    }
    
    /**
     * 
     * @param agentId
     * @return
     */
    @RequestMapping(value = "/{agentId}", method = RequestMethod.DELETE)
    public @ResponseBody String onDelete(@Preloading("id") Agent agent) {
        Result result = new Result();
        
        try {
            agentService.deleteAgent(agent);
            
            result.success().message("删除代言人成功");
            
        } catch (Exception e) {
            
            logger.error("onDelete() - ", e);
            result.fail().message("删除代言人失败");
        }
        
        return JsonUtils.toJsonString(result);
    }
    
    /**
     * 
     * @return
     */
    @RequestMapping(value = "/export", method = RequestMethod.GET)
    public ModelAndView onExport() {
        ModelAndView modelAndView = new ModelAndView(new ExcelTemplateView("agent-statistics.xls"));
        
        List<Agent> agents = agentService.listAgent();
        modelAndView.addObject("agents", agents);
        
        return modelAndView;
    }
}
